import os
import time
from concurrent.futures import ProcessPoolExecutor  # ProcessPoolExecutor 基于 multiprocessing
import multiprocessing as mp

def test():
    pid = os.fork()
    if pid == 0:
        # 子进程中pid为0
        print('子进程中执行，子进程ID:{},父进程ID:{}'.format(os.getpid(), os.getppid()))
    else:
        print("父进程中执行，子进程ID:{},进程ID:{}".format(pid, os.getpid()))

    time.sleep(2)


def get_html(n):
    time.sleep(n)
    print("sub process success")
    return n

def test_process():
    progrss=mp.Process(target=get_html,args=(2,))
    progrss.start()
    progrss.join()
    print("process success")

# 线程池
def test_process_pool():
    #不指定processes 默认为cpu数量
    pool=mp.Pool(processes=4)
    resutl=pool.apply_async(get_html,args=(2,))

    pool.close() # 需要先关闭线程池，不然线程池会一直运行，从而导致join运行不了
    pool.join()
    print("process pool success",resutl.get())

    for res in mp.imap(get_html,[1,2,3]):
        print("imap res:{}".format(res))

def test_process_pool_imap():
    pool = mp.Pool(processes=4)

    #按顺序输出结果
    for res in pool.imap(get_html,[1,2,3]):
        print("imap res:{}".format(res))


    # 谁先完成谁打印
    for res in pool.imap_unordered(get_html,[3,2,1]):
        print("imap res:{}".format(res))

    pool.close()
    pool.join()

if __name__ == '__main__':
    test_process_pool_imap()